import time

from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import csv
import json


class Wechat_Moment():
	def __init__(self):
		desired_caps = {}
		desired_caps['platformName'] = 'Android'
		desired_caps['platformVersion'] = '5.1.1'
		desired_caps['deviceName'] = '42e23049727d4105'

		desired_caps['appPackage'] = 'com.tencent.mm'
		desired_caps['appActivity'] = '.ui.LauncherUI'
		desired_caps['noReset'] = True

		# 定义在朋友圈的时候滑动位置
		self.start_x = 300
		self.start_y = 800
		self.end_x = 300
		self.end_y = 300

		# 启动微信
		self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
		# 设置等待
		self.wait = WebDriverWait(self.driver, 300)
		print('微信启动...')

		# 写入文件做词云分析
		self.f = open('detail.json', 'w', encoding='utf-8')

	def login(self):
		# 获取到登录按钮后点击
		login_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/e4g")))
		login_btn.click()
		# 获取使用微信号登录按钮
		change_login_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/cou")))
		change_login_btn.click()
		# 获取输入账号元素并输入
		account = self.wait.until(
			EC.presence_of_element_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/cos"]/android.widget.EditText')))
		account.send_keys("xxxxxxxx")
		# 获取密码元素并输入
		password = self.wait.until(
			EC.presence_of_element_located((By.XPATH, '//*[@resource-id="com.tencent.mm:id/cot"]/android.widget.EditText')))
		password.send_keys("xxxxxx")
		# 登录
		login = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/cov")))
		login.click()
		# 点击去掉通讯录提示框
		no_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/az9")))
		no_btn.click()
		print('登录成功...')

	def find_xiaoshuaib(self):
		# 获取到搜索按钮后点击
		search_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/jb")))
		# 等搜索建立索引再点击
		# time.sleep(10)
		search_btn.click()
		# 获取搜索框并输入
		search_input = self.wait.until(EC.presence_of_element_located((By.ID, "com.tencent.mm:id/l3")))
		search_input.send_keys("h735132710")
		# search_input.send_keys("ii19960710")
		print('搜索小帅b...')
		# 点击头像进入
		xiaoshuaib_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/qk")))
		xiaoshuaib_btn.click()
		# 点击右上角...进入
		menu_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/kj")))
		menu_btn.click()
		# 再点击头像
		icon_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/e3x")))
		icon_btn.click()
		# 点击朋友圈
		moment_btn = self.wait.until(EC.element_to_be_clickable((By.ID, "com.tencent.mm:id/d9v")))
		moment_btn.click()
		print('进入朋友圈...')

	def get_data(self):
		while True:
			# 获取 ListView
			items = self.wait.until(EC.presence_of_all_elements_located((By.ID, 'com.tencent.mm:id/eii')))
			# 滑动
			self.driver.swipe(self.start_x, self.start_y, self.end_x, self.end_y, 2000)
			# 遍历获取每个List数据
			year = '2019年'
			month = ''
			day = ''

			for item in items:
				try:
					# 可能获取不到年份, 就用上次获取到的年份 (在同一年)
					year = item.find_element_by_id('com.tencent.mm:id/eo4').text
				except:
					pass
				try:
					# 一天发送多个消息可能没有日期, 就用上次获取到的月和日 (在同一天)
					month = item.find_element_by_id('com.tencent.mm:id/eo3').text
					day = item.find_element_by_id('com.tencent.mm:id/eo2').text
				except:
					pass

				moment_text = item.find_element_by_id('com.tencent.mm:id/o7').text
				detail_json = json.dumps({'发送时间': self.date_format(year + month + day), '发送内容': moment_text}, ensure_ascii=False)
				print(detail_json)
				self.f.writelines(detail_json + '\r\n')
				self.f.flush()

	def date_format(self, datetime):
		"""
		处理时间
		:param datetime: 原始时间
		:return: 处理后时间
		"""
		if re.match('\d+分钟前', datetime):
			minute = re.match('(\d+)', datetime).group(1)
			datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - float(minute) * 60))
		if re.match('\d+小时前', datetime):
			hour = re.match('(\d+)', datetime).group(1)
			datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - float(hour) * 60 * 60))
		if re.match('昨天', datetime):
			datetime = time.strftime('%Y-%m-%d', time.localtime(time.time() - 24 * 60 * 60))
		if re.match('\d+天前', datetime):
			day = re.match('(\d+)', datetime).group(1)
			datetime = time.strftime('%Y-%m-%d', time.localtime(time.time()) - float(day) * 24 * 60 * 60)

		# 最后是我加的, 把年月日组合起来
		dat_li = re.sub(r'\D', '-', datetime, 2).split('-')
		tmp = ''
		for i in dat_li:
			if len(i) < 2:
				tmp += '%.2d' % int(i) + '-'
			else:
				tmp += i + '-'
		datetime = tmp[:-1]

		return datetime


if __name__ == '__main__':
	wc_moment = Wechat_Moment()
	# wc_moment.login()
	wc_moment.find_xiaoshuaib()
	wc_moment.get_data()
